package pro.softzhang.algo.lc500;

import java.util.LinkedList;
import java.util.Queue;

public class LC542_ZeroOneMatrix {
    public static void main(String[] args) {

    }

    static class Solution {
        public int[][] updateMatrix(int[][] mat) {
            int width = mat.length, length = mat[0].length;
            int[][] dmat = new int[width][length];
            Queue<int[]> q = new LinkedList<>();
            for (int i = 0; i < width; i++) {
                for (int j = 0; j < length; j++) {
                    if(mat[i][j] == 0) {
                        q.add(new int[]{i, j});
                        dmat[i][j] = 0;
                    } else {
                        dmat[i][j] = Integer.MAX_VALUE;
                    }
                }
            }

            int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
            while (!q.isEmpty()) {
                int[] pos = q.remove();
                int distance = dmat[pos[0]][pos[1]];
                for (int[] dir : dirs) {
                    int r = pos[0] + dir[0];
                    int c = pos[1] + dir[1];
                    if(r >= 0 && c >= 0 && r < width && c < length) {
                        if(dmat[r][c] > distance + 1) {
                            dmat[r][c] = distance + 1;
                            q.add(new int[]{r, c});
                        }
                    }
                }
            }
            return dmat;
        }
    }
}
